<template>
  <ele-page class="p-0!" flex-table>
    <ele-bottom-bar v-if="current" :teleported="true">
      <template #extra>
        <template v-if="showEdit">
          <el-button type="info" @click="showEdit = false">返回</el-button>
          <el-button type="primary" :loading="loading" :disabled="!current.product_list.some(v => v.post_num > 0)" @click="save()">保存</el-button>
        </template>
        <template v-else>
          <el-button v-if="current.is_qx === 1" type="info" @click="cancel()">取消</el-button>
          <el-button v-if="current.is_start === 1" type="primary" plain @click="confirm()">开始验货</el-button>
          <el-button v-if="current.is_yh === 1" type="primary" plain @click="openEdit()">验货</el-button>
        </template>
      </template>
    </ele-bottom-bar>
    <ele-split-panel
      flex-table
      size="280px"
      allow-collapse
      :custom-style="{ borderWidth: '0 1px 0 0', padding: '5px 0' }"
      :body-style="{ padding: '16px 16px 0 0', overflow: 'hidden' }"
      :style="{ height: '100%', overflow: 'visible' }"
    >
      <ele-loading
        :loading="loading"
        :style="{ flex: 1, paddingRight: '10px', overflow: 'auto' }"
      >
        <el-tree
          ref="treeRef"
          :data="treeData"
          highlight-current
          node-key="id"
          :props="{ label: 'pick_order_sn' }"
          :expand-on-click-node="false"
          :default-expand-all="true"
          :filter-node-method="filterNode"
          :style="{
            '--ele-tree-item-height': '40px',
            '--ele-tree-expand-padding': 0,
            '--ele-tree-expand-margin': 0,
          }"
          @node-click="onNodeClick"
        >
          <template #default="{ data: d }">
            <div class="el-tree-node__label flex-ba w-full">
              <div style="margin-right: 4px">{{ d.pick_order_sn }}</div>
              <el-tag :type="getType(d.status)">
                {{ d.status_name }}
              </el-tag>
            </div>
          </template>
        </el-tree>
      </ele-loading>
      <template #body>
        <template v-if="current">
          <el-descriptions title="验收单详情" :column="4">
            <el-descriptions-item :width="100" label="拣货单号">
              {{ current.pick_order_sn || '-' }}
            </el-descriptions-item>

            <el-descriptions-item :width="100" label="状态">
              <el-tag :type="getType(current.status, { YS: 'danger' })">{{ current.status_name }}</el-tag>
            </el-descriptions-item>

            <el-descriptions-item :width="100" label="创建人">
              {{ current.create_user_name || '-' }}
            </el-descriptions-item>

            <el-descriptions-item :width="100" label="创建时间">
              {{ current.create_time ? formatDate(current.create_time) : '-' }}
            </el-descriptions-item>
          </el-descriptions>
          <el-table
            :data="current.product_list"
            style="width: 100%"
            show-summary
            :summary-method="getSummaries"
            row-key="product_id"
            class="form-table"
          >
            <el-table-column type="index" label="序" width="60" align="center" />
            <el-table-column prop="product_name" label="商品名称" align="left" min-width="130" />
            <el-table-column prop="product_code" label="商品编码" align="center" />
            <el-table-column prop="unit" label="主单位" align="center" />
            <el-table-column prop="num" label="商品数量" align="center" />
            <el-table-column prop="pick_num" label="拣货数量" align="center" />
            <el-table-column prop="inspect_num" label="验货数量" align="center" />
            <el-table-column v-if="showEdit" prop="post_num" label="本次验货数量" align="center" min-width="100">
              <template #default="{ row }">
                <div class="flex-c">
                  <el-input
                    v-model="row.post_num"
                    class="w-100px!"
                    placeholder="数量"
                    oninput="value=value.replace(/[^\d.]/g, '').replace(/^\D*([0-9]\d*\.?\d{0,2})?.*$/,'$1')"
                    :disabled="!row.max"
                    @blur="row.post_num = checkMax(row)"
                  >
                    <template #suffix><span class="text-#333!">{{ row.unit }}</span></template>
                  </el-input>
                </div>
              </template>
            </el-table-column>
            <el-table-column prop="location" label="库位" :formatter="row => row.location.map(v => v.name).toString()" align="center" />
          </el-table>
        </template>
      </template>
    </ele-split-panel>
  </ele-page>
</template>

<script setup>
const props = defineProps({
  orderId: Number,
})

const emit = defineEmits(['done'])

const { formatDate, getType } = utils

const showEdit = ref(false)

const loading = ref(false)
const treeRef = ref(null)
const current = ref(null)
const treeData = ref([])

function checkMax(row) {
  return utils.Big(row.post_num).gt(row.max) ? row.max : row.post_num
}

function cancel() {
  utils.confirm(`是否确定取消拣货单 ${current.value.pick_order_sn}`, '提示').then(() => {
    utils.post('/outboundPick/cancel', { pick_order_sn: current.value.pick_order_sn }).then((res) => {
      utils.message(res.msg, res.success)
      if (res.success) {
        query()
      }
    })
  })
}

function confirm() {
  utils.confirm('是否确定开始验货', '提示').then(() => {
    utils.post('/outboundInspect/start', { pick_order_id: current.value.id }).then((res) => {
      utils.message(res.msg, res.success)
      if (res.success) {
        query()
        showEdit.value = true
      }
    })
  })
}

function openEdit() {
  current.value.product_list.forEach((v) => {
    const max = utils.Big(v.pick_num).minus(v.inspect_num).toNumber()
    v.post_num = ''
    v.max = max > 0 ? max : 0
  })
  showEdit.value = true
}

async function save() {
  const inspect_list = current.value.product_list.filter(d => d.post_num > 0).map(v => ({
    outbound_pick_product_id: v.id,
    num: v.post_num,
  }))
  if (!inspect_list.length) {
    return utils.message('请填写验货数量', 'error')
  }
  loading.value = true
  await utils.sleep(100)
  const formData = {
    outbound_id: props.orderId,
    outbound_pick_id: current.value.id,
    inspect_list,
  }
  utils.post('/outboundInspect/batchRecord', formData)
    .then((res) => {
      utils.message(res.msg, res.success)
      if (res.success) {
        query()
      }
    })
    .finally(() => {
      loading.value = false
    })
}

/** 树过滤方法 */
function filterNode(value, data) {
  if (value)
    return !!(data.order_sn && data.order_sn.includes(value))

  return true
}

/** 选择数据 */
function onNodeClick(row) {
  if (row?.id) {
    current.value = row
    treeRef.value?.setCurrentKey?.(row.id)
  }
  else {
    current.value = null
  }
  showEdit.value = false
}

/** 查询 */
function query(isfirst) {
  loading.value = true
  utils.get('/outbound/pickList', { outbound_id: props.orderId }).then((res) => {
    treeData.value = res.data
    if (res.data.length) {
      nextTick(() => {
        const row = res.data.find(v => v.id === current.value?.id) ?? res.data[0]
        onNodeClick(row)
      })
    }
  }).finally(() => {
    loading.value = false
  })
  if (!isfirst) {
    emit('done')
  }
}

query(true)

function getSummaries({ columns, data }) {
  const sums = []
  columns.forEach((column, index) => {
    if (index === 0) {
      sums[index] = '合计'
      return
    }
    const keys = ['num', 'pick_num', 'inspect_num', 'post_num']
    if (keys.includes(column.property)) {
      sums[index] = data.reduce((acc, cur) => utils.Big(acc).plus(cur[column.property]).valueOf(), 0)
    }
    else {
      sums[index] = ''
    }
  })

  return sums
}
</script>

<style lang="scss" scoped>

</style>
